#include "SQliteDataBase.h"

SQliteDataBase::SQliteDataBase()
{
    m_Db = NULL;
}

SQliteDataBase::~SQliteDataBase()
{
    close();
}

bool SQliteDataBase::connectDB(const string &connStr)
{

    /* 打开数据 */
    int ret = sqlite3_open(connStr.c_str(), &m_Db);
    if(ret != SQLITE_OK)
    {
        std::cout << " sqlite3 error" << sqlite3_errmsg(m_Db) << endl;
        return false;
    }
    
    return true;
}

bool SQliteDataBase::executeSql(const string &sql)
{
    int ret = sqlite3_exec(m_Db, sql.c_str(), NULL, NULL, NULL);
    if(ret != SQLITE_OK)
    {
        std::cout << " sqlite3 exec error" << sqlite3_errmsg(m_Db) << endl;
        return false;
    }

    return true;
}

QueryResult SQliteDataBase::querySql(const string &sql)
{
    char **result = NULL;
    int row = 0;
    int column = 0;
    QueryResult res;

    if (m_Db == nullptr) 
    {
        std::cerr << "Database not initialized." << std::endl;
        return res;
    }

    int ret = sqlite3_get_table(m_Db, sql.c_str(), &result, &row, &column, NULL);
    if (ret != SQLITE_OK)
    {
        std::cerr << "sqlite3 get table error: " << sqlite3_errmsg(m_Db) << std::endl;
        return res;
    }

    for (int idx = 0; idx < column; idx++)
    {
        res.columnName.push_back(result[idx]);
    }

    for (int i = 1; i <= row; i++)
    {
        vector<string> temp;
        for (int j = 0; j < column; j++)
        {
            temp.push_back(result[i * column + j]);  // 填充每行数据
        }
        res.rows.push_back(temp);  // 填入二维数组
    }

    sqlite3_free_table(result);  // 释放表格数据
    return res;
}


void SQliteDataBase::close()
{
    if (m_Db) 
    {
        sqlite3_close(m_Db);
        m_Db = nullptr; // 设置为空指针，防止段错误
    }

}
